﻿using AuthCenter_Comons;
using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command.ReversoaLL;
using AuthCenter_HuangJingtao.Read.Api.Dto;
using Dm.filter;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler.ReversoaLL
{

    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult<ShowDto>>
    {

        private readonly IConfiguration _configuration;
        IBaseReponsitory<Roles> Roles;
        IBaseReponsitory<App> Apps;
        IBaseReponsitory<RoleApp> RoleApp;

        public LoginCommandHandler(IBaseReponsitory<Roles> Roles, IBaseReponsitory<App> Apps, IBaseReponsitory<RoleApp> RoleApp, IConfiguration _configuration)
        {
            this.Roles = Roles;
            this.Apps = Apps;
            this.RoleApp = RoleApp;
            this._configuration = _configuration;
        }

        public async Task<ApiResult<ShowDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var jwtTools = new JwtTools(); // 假设包含该方法的类名是 JwtTools
            var list = from a in Apps.GetQuery()
                       join e in RoleApp.GetQuery() on a.App_Id equals e.App_Id
                       join f in Roles.GetQuery() on e.Role_Id equals f.Role_Id
                       where a.App_Name == request.Name && a.App_PassWord == request.Password
                       select new ShowDto
                       {
                           App_Id = a.App_Id,
                           App_Name = a.App_Name,
                           App_Sex = a.App_Sex,
                           AddressId = a.AddressId,
                           App_Discription = a.App_Discription,
                           App_People = a.App_People,
                           Role_Name = "",//所有角色名称
                           Role_Id = e.Role_Id,
                           Role_ArrId = a.Role_ArrId,
                           Group_Id = a.Group_Id,
                           App_IsDel = a.App_IsDel,
                           Token= ""
                       };
            list = list.Where(x => !x.App_IsDel);
            var tlist = await list.FirstOrDefaultAsync();

            if (tlist != null)
            { 
                string token = jwtTools.JwtNewString(_configuration, tlist.App_Id.ToString());
                tlist.Token = token;
                return new ApiResult<ShowDto>
                {
                    Code = ApiEnum.Success,
                    Message = token,
                    Data = tlist
                };

            }
            else 
            {
                return new ApiResult<ShowDto>
                {
                    Code = ApiEnum.False,
                    Message = "账号或者密码错误",
                    Data = tlist
                };
            }
        }
    }
}
